package com.ryan.dispatcher.comp;

import com.ryan.dispatcher.ResourceTable;
import com.ryan.dispatcher.ability.ArgsAbility;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

public class PagerFraction extends Fraction {

    private final int index;

    public PagerFraction(int index) {
        this.index = index;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        return scatter.parse(ResourceTable.Layout_item_pager, null, false);
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
//
//        Text text = (Text) getComponent().findComponentById(ResourceTable.Id_item_text);
//        text.setText("text" + index);
        initList();
    }

    private void initList() {
        ListContainer container = (ListContainer) getComponent().findComponentById(ResourceTable.Id_list);
        container.setItemProvider(new SampleProvider());

        container.setItemClickedListener((list, component, position, id) -> {
            new ToastDialog(component.getContext())
                    .setText("you clicked:" + position)
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
        });
    }

    class SampleProvider extends BaseItemProvider {

        @Override
        public int getCount() {
            return 100;
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int position, Component convert, ComponentContainer container) {
            final Component cpt;
            if (convert == null) {
                cpt = LayoutScatter.getInstance(container.getContext()).parse(ResourceTable.Layout_item, null, false);
            } else {
                cpt = convert;
            }

            Text text = (Text) cpt.findComponentById(ResourceTable.Id_item_text);
            text.setText("text" + index + " " + position);
            return cpt;
        }
    }
}
